/**
 * 布局视图组件
 * 渲染排班表的主要布局结构
 */

import { useState, useEffect } from 'react'
import type { PluginComponentProps, ViewMode, Employee, Shift } from '../../types'
import { ScheduleEvents } from '../../types'
import { Header } from './components/Header'
import { EmployeeList } from './components/EmployeeList'
import { ScheduleGrid } from './components/ScheduleGrid'

export function LayoutView({ context }: PluginComponentProps) {
  const [employees, setEmployees] = useState<Employee[]>([])
  const [shifts, setShifts] = useState<Shift[]>([])
  const [viewMode, setViewMode] = useState<ViewMode>('week')
  const [dateRange, setDateRange] = useState(context.getDateRange())

  // 初始化数据（只在组件挂载时执行一次）
  useEffect(() => {
    setEmployees(context.getEmployees())
    setShifts(context.getShiftsByDateRange(dateRange.start, dateRange.end))
    setViewMode(context.getViewMode())
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  // 监听数据变化
  useEffect(() => {
    const unsubscribers = [
      // 员工变化
      context.on(ScheduleEvents.EMPLOYEE_ADDED, () => {
        setEmployees(context.getEmployees())
      }),
      context.on(ScheduleEvents.EMPLOYEE_UPDATED, () => {
        setEmployees(context.getEmployees())
      }),
      context.on(ScheduleEvents.EMPLOYEE_REMOVED, () => {
        setEmployees(context.getEmployees())
      }),

      // 班次变化
      context.on(ScheduleEvents.SHIFT_ADDED, () => {
        setShifts(context.getShiftsByDateRange(dateRange.start, dateRange.end))
      }),
      context.on(ScheduleEvents.SHIFT_UPDATED, () => {
        setShifts(context.getShiftsByDateRange(dateRange.start, dateRange.end))
      }),
      context.on(ScheduleEvents.SHIFT_REMOVED, () => {
        setShifts(context.getShiftsByDateRange(dateRange.start, dateRange.end))
      }),

      // 视图模式变化
      context.on(ScheduleEvents.VIEW_CHANGED, (mode: ViewMode) => {
        setViewMode(mode)
      }),

      // 日期范围变化
      context.on(ScheduleEvents.DATE_RANGE_CHANGED, range => {
        setDateRange(range)
        setShifts(context.getShiftsByDateRange(range.start, range.end))
      }),
    ]

    return () => {
      unsubscribers.forEach(unsub => unsub())
    }
  }, [context, dateRange.start, dateRange.end])

  return (
    <div className="layout-plugin">
      <Header context={context} viewMode={viewMode} dateRange={dateRange} />

      <div className="layout-body">
        <EmployeeList employees={employees} />
        <ScheduleGrid
          context={context}
          employees={employees}
          shifts={shifts}
          dateRange={dateRange}
          viewMode={viewMode}
        />
      </div>
    </div>
  )
}
